//
//  FXEmoticonTools.swift
//  微博(Swift)
//
//  Created by V on 16/1/13.
//  Copyright © 2016年 V. All rights reserved.
//

import UIKit

class FXEmoticonTools: NSObject {
    static let sharedTools: FXEmoticonTools = FXEmoticonTools()
    /// 表情数据的 bundle
    lazy var emoticonBundle: NSBundle = {
        // 获取 bundle 路径
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)
        return NSBundle(path: path!)!
    }()
    
    // 最近表情
    private lazy var recentEmoticons: [FXEmoticon] = {
       return [FXEmoticon]()
    }()
    // 默认表情整体数组
    private lazy var defaultEmoticons: [FXEmoticon] = {
        return self.emoticonsWithPath("default/info.plist")
    }()
    
    /// emoji
    private lazy var emojiEmoticons: [FXEmoticon] = {
        return self.emoticonsWithPath("emoji/info.plist")
    }()
    
    /// 浪小花
    private lazy var lxhEmoticons: [FXEmoticon] = {
        return self.emoticonsWithPath("lxh/info.plist")
    }()
    
    /// 表情数组最关键的
    /// collectionView 显示的内容全部来至于此
    lazy var allEmoticons: [[[FXEmoticon]]] = {
        return [
            self.pagesWithEmotions(self.recentEmoticons),
            self.pagesWithEmotions(self.defaultEmoticons),
            self.pagesWithEmotions(self.emojiEmoticons),
            self.pagesWithEmotions(self.lxhEmoticons)
        ]
    }()
    
    
    // 将传入的表情数组，分成20个一个小数组并一起返回
    private func pagesWithEmotions(emoticons: [FXEmoticon]) -> [[FXEmoticon]] {
        // 1. 求出一共分为多少页
        let pageCount = (emoticons.count - 1) / 20 + 1
        var result: [[FXEmoticon]] = [[FXEmoticon]]()
        for i in 0..<pageCount {
            // 计算从哪儿开始截取
            let location = i * 20
            // 一页截取多少个
            var length = 20
            // 判断是否数组越界
            if location + length > emoticons.count {
                length = emoticons.count - location
            }
            // 初始化 range
            let range = NSMakeRange(location, length)
            // 截取子数组
            let pageEmoticons = (emoticons as NSArray).subarrayWithRange(range) as! [FXEmoticon]
            result.append(pageEmoticons)
        }
        return result
    }

    
    
    private func emoticonsWithPath(path: String) -> [FXEmoticon] {
        // 获取 plist 文件路径
        let file = emoticonBundle.pathForResource(path, ofType: nil)!
        // 把 plist 文件转成 字典数组
        let emoticonDictArray = NSArray(contentsOfFile: file)!
        // 遍历数组字典转模型
        // 定义一个空数组 用来装模型
        var result = [FXEmoticon]()
        for dict in emoticonDictArray {
            let emoticon = FXEmoticon(dict: dict as! [String: AnyObject])
            
            // NSString *path = @"/Users/username/file.txt";
            //￼ 删除最后部分的组成部分 结果: /Users/username
            // NSString *filePath = [path stringByDeletingLastPathComponent];
            emoticon.path = (path as NSString).stringByDeletingLastPathComponent
            result.append(emoticon)
        }
        return result
    }
}
